from appserver import db_store
from sqlalchemy import func
import copy


class ModelBase(db_store.Model):
    __abstract__ = True    # 使ModelBase不必与数据表关联,不生成表

    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')

    def __init__(self):
        self.id = 0
    ####获取字典的值,给模型赋值,保存进数据库, 保存进数据库的时候调用,
    def from_dict(self, rev_source):
        # 深拷贝一下,获取一个新的字典,防止遍历时出错
        source = copy.deepcopy(rev_source)
        if "level" in source:
            source["depth"] = source.pop("level")
        if "children" in source:
            source.pop("children")
        if "roles_id" in source:
            source.pop('roles_id')
        for k in source:
            try:
                getattr(self, k)
                # print(444, getattr(self, k))
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])
    # 返回字典,key是c.name ,值是 字段的值, 返回给前端时调用
    def to_dict(self):
        return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}

    def get_max_id(self):
        val = db_store.session.query(func.max(self.__class__.id)).scalar()
        if not val:
            return 0
        else:
            return val

    def save(self):
        try:
            if self.id == 0:  # 新增数据
                self.id = self.get_max_id() + 1
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def delete(self):
        try:
            db_store.session.delete(self)
            db_store.session.commit()
            return True
        except Exception as err:
            print(err)
            db_store.session.rollback()
            return False

    def get_entity_by_id(self, id):
        return copy.deepcopy(self.query.filter_by(id=id).first())

    def get_list_all(self):
        return self.query.all()
